<?php

namespace App\Http\Controllers\Order;

use App\Http\Controllers\BaseController;
use App\Http\Validate\Custom\Custom;
use App\Http\Validate\Order\Saleorderinvoice;
use App\Models\Custom\Custom as ModelCustom;
use App\Models\Order\Outboundorder;
use App\Models\Order\Saleorder;
use App\Services\Common\TableExtFeild;
use Illuminate\Http\Request;
use App\Models\Order\Saleorderinvoice as ModelSaleorderinvoice;
use Illuminate\Support\Facades\DB;

/**
 * 销售订单，预开发票管理
 */
class OrderinvoiceController extends BaseController
{
    /**
     * 获取表头
     */
    public function gettablefield()
    {
        $cpid = $this->mangerinfo['cpid'];
        $mainextfield = TableExtFeild::getFeildTitle((new ModelSaleorderinvoice())->getTable(), $cpid);
        return response()->json([
            'code' => '000',
            'msg' => '获取成功',
            'data' => ['mainextfield' => $mainextfield]
        ]);
    }

    /**
     * 编辑表头字段
     */
    public function changeorderfield(Request $request)
    {
        $id = $request->id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = ModelSaleorderinvoice::where(['id' => $id, 'manger_id' => $manger_id, 'cpid' => $cpid])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $data = TableExtFeild::getTableFeildData($request);
        ModelSaleorderinvoice::where(['id' => $id, 'manger_id' => $manger_id, 'cpid' => $cpid])->update($data);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 添加
     */
    public function dopostadd(Request $request)
    {
        //校验参数
        $params = [
            'id',
            'type',
            'category',
            'company_code',
            'company_name',
            'company_contacts',
            'order_number',
            'document_number',
            'document_date',
            'firm_name',
            'credit_code',
            'firm_address',
            'firm_phone_number',
            'firm_bank',
            'firm_bank_number',
            'firm_email',
            'business_license',
            'account_opening_permit',
            'attorney',
            'balance',
        ];
        $req_data = $request->only($params);
        $validate = new Saleorderinvoice('add');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        //判断订单是否存在
        $id = $req_data['id'];
        //预开发票
        if ($req_data['type'] == 1) {
            $isexist = Saleorder::where('id', $id)->first();
        } else {
            $isexist = Outboundorder::where('id', $id)->first();
        }
        if (!$isexist) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        $orderNumber = $isexist->order_number;

//        else {
//            $custom_id = $isexist->custom_id;
//        }

//        $custom = ModelCustom::where('id', $custom_id)->first()->toArray();
//        $bank = json_decode($custom['bank_info'], true);
//        if ($bank) {
//            foreach ($bank as $v) {
//                if ($v['is_default'] == 1) {
//                    $company_contacts = $v['contacts'];
//                }
//            }
//        } else {
//            $company_contacts = '';
//        }
        //出库单是否已经申请开票
        $outbound_status = Outboundorder::where('order_number',$orderNumber)
            ->where('invoice_status', '>',config('constants.invoice_status.not_invoiced'))
            ->exists();

        if($outbound_status)
        {
            return response()->json(['code' => '001', 'msg' => '订单已开票']);
        }
        //订单状态能否开票
//        $invoice_status = $isexist->invoice_status;
//        $allow_invoice = [
//            config('constants.invoice_status.not_invoiced'),
//            config('constants.invoice_status.reject'),
//        ];
//        if (!in_array($invoice_status, $allow_invoice)) {
//            return response()->json(['code' => '001', 'msg' => '订单已开票']);
//        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $sys_dpm_id = $mangerinfo['sys_dpm_id'] ?? 0;


        $data = [
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'type' => $req_data['type'],
            'category' => $req_data['category'],
            'custom_id' => $req_data['balance']['custom_id'] ?? 0,
            'company_code' => $req_data['company_code'],
            'company_name' => $req_data['company_name'],
            'order_number' => $req_data['order_number'],
            'document_number' => $req_data['document_number'],
            'document_date' => $req_data['document_date'],
            'firm_name' => $req_data['firm_name'],
            'credit_code' => $req_data['credit_code'],
            'firm_address' => $req_data['firm_address'],
            'firm_phone_number' => $req_data['firm_phone_number'],
            'firm_bank' => $req_data['firm_bank'],
            'firm_bank_number' => $req_data['firm_bank_number'],
            'firm_email' => $req_data['firm_email'],
            'business_license' => $req_data['business_license'],
            'account_opening_permit' => $req_data['account_opening_permit'],
            'attorney' => $req_data['attorney'],
            'company_contacts' => $req_data['company_contacts'],
            'status' => config('constants.order_invoice.not_invoiced'),
            'sys_dpm_id' => $sys_dpm_id,
            'create_at' => time(),
        ];

        // 判断 order_number 是否已存在
        $existingRecord = ModelSaleorderinvoice::where('order_number', $orderNumber)->first();

        DB::beginTransaction();
        try {
            //更新订单开票状态
            if ($req_data['type'] == 1) {
                Saleorder::where('id', $id)->update([
                    'invoice_status' => config('constants.invoice_status.invoicing'),
                    'update_at' => time()
                ]);
            }
//            else {
//                Outboundorder::where('id', $id)->update([
//                    'invoice_status' => config('constants.invoice_status.invoicing'),
//                    'update_at' => time()
//                ]);
//            }
            if ($existingRecord) {
                // 存在，执行更新操作
                ModelSaleorderinvoice::where('order_number', $orderNumber)->update($data);
            } else {
                // 不存在，执行新增操作
                ModelSaleorderinvoice::create($data);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '开票失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = ModelSaleorderinvoice::getList($request, $memberinfo, $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 会计，开票、补开
     * 补开状态的不能驳回
     */
    public function invoice(Request $request)
    {
        //校验参数
        $params = ['id', 'status', 'invoice_number'];
        $req_data = $request->only($params);
        $validate = new Saleorderinvoice('invoice');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        //判断订单是否存在
        $id = $req_data['id'];
        $one = ModelSaleorderinvoice::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }

        DB::beginTransaction();
        try {
            $data = [
                'status' => $req_data['status'],
                'invoice_number' => $req_data['invoice_number'],
                'update_at' => time()
            ];
            ModelSaleorderinvoice::where('sale_order_id', $id)->update($data);

            //更新订单开票状态
            $data = [
                'invoice_status' => $req_data['status'],
                'update_at' => time()
            ];
            if ($req_data['type'] == 1) {
                Saleorder::where('id', $id)->update($data);
            } else {
                Outboundorder::where('id', $id)->update($data);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '开票失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 详情
     */
    public function getone(Request $request)
    {
        $id = $request->id ?? 0;
        $one = ModelSaleorderinvoice::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '发票不存在']);
        }
        $one = $one->toArray();
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
    }

    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        //校验参数
        $params = [
            'id',
            'type',
            'category',
            'company_code',
            'company_contacts',
            'order_number',
            'document_number',
            'document_date',
            'firm_name',
            'credit_code',
            'firm_address',
            'firm_phone_number',
            'firm_bank',
            'firm_bank_number',
            'firm_email',
            'business_license',
            'account_opening_permit',
            'attorney',
        ];
        $req_data = $request->only($params);
        $validate = new Saleorderinvoice('add');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        //判断开票是否存在
        $id = $req_data['id'];
        if ($req_data['type'] == 1) {
            $isexist = Saleorder::where('id', $id)->first();
        } else {
            $isexist = Outboundorder::where('id', $id)->first();
        }
        if (!$isexist) {
            return response()->json(['code' => '001', 'msg' => '开票不存在']);
        }
        $one = ModelSaleorderinvoice::where('order_number', $req_data['order_number'])->first();

        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '开票信息不存在']);
        }
        $one = $one->toArray();

        //未开票，驳回可以编辑
        if (
            $one['status'] != config('constants.order_invoice.not_invoiced')
            && $one['status'] != config('constants.order_invoice.reject')
        ) {
            return response()->json(['code' => '001', 'msg' => '订单已审核，不可以编辑']);
        }

        $data = [
            'company_code' => $req_data['company_code'],
            //            'company_contacts' => $req_data['company_contacts'],
            'order_number' => $req_data['order_number'],
            'document_number' => $req_data['document_number'],
            'document_date' => $req_data['document_date'],
            'firm_name' => $req_data['firm_name'],
            'credit_code' => $req_data['credit_code'],
            'firm_address' => $req_data['firm_address'],
            'firm_phone_number' => $req_data['firm_phone_number'],
            'firm_bank' => $req_data['firm_bank'],
            'firm_bank_number' => $req_data['firm_bank_number'],
            'firm_email' => $req_data['firm_email'],
            'business_license' => $req_data['business_license'],
            'account_opening_permit' => $req_data['account_opening_permit'],
            'attorney' => $req_data['attorney'],
            'status' => config('constants.order_invoice.not_invoiced'),
            'update_at' => time(),
        ];

        ModelSaleorderinvoice::where('order_number', $req_data['order_number'])->update($data);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }
}
